<template>
    <el-text type="primary" size="large">
        <h1 class="my-h1">商品管理</h1>
    </el-text>


    <el-table :data="goodsData" style="width: 100%">
        <el-table-column fixed prop="gid" label="商品ID" width="80" />
        <el-table-column prop="name" label="商品名称" width="100" />
        <el-table-column label="商品类型" width="120">
            <template #default="scope">
                {{ getTypeName(scope.row.tid) }}
            </template>
        </el-table-column>
        <el-table-column prop="cover" label="商品图片" width="200">
            <template #default="scope">
                <el-link :href="scope.row.cover" target="_blank">
                    <el-tooltip :content="scope.row.cover" placement="top-start">
                        <el-image style="width: 100px;height: 100px;border: 1px lightgray solid;" :src="scope.row.cover"
                            fit="cover">
                            <template #error>
                                <el-text style="font-size: 14px;">
                                    {{ "图片无法展示" }}
                                </el-text>
                            </template>
                        </el-image>
                    </el-tooltip>
                </el-link>
            </template>
        </el-table-column>
        <el-table-column prop="price" label="商品价格" width="100" />
        <el-table-column prop="stock" label="商品库存" width="100" />
        <el-table-column prop="intro" label="商品描述" width="200">
            <template #default="scope">
                <el-text truncated>
                    <el-tooltip :content="scope.row.intro" placement="top-start">
                        {{ scope.row.intro }}
                    </el-tooltip>
                </el-text>
            </template>
        </el-table-column>
        <el-table-column prop="createTime" label="上架时间" width="200" />
        <el-table-column prop="updateTime" label="最后一次更新时间" width="200" />
        <el-table-column fixed="right" label="操作" width="200">
            <template #default="scope">
                <el-button plain type="primary" size="small" @click="updateGoods(scope.row)">修改</el-button>
                <el-button plain type="warning" size="small" @click="recommendGoods(scope.row)">推荐</el-button>
                <el-button plain type="danger" size="small" @click="deleteGoods(scope.row)">删除</el-button>
            </template>
        </el-table-column>
    </el-table>


    <el-row style="margin-top: 20px;justify-content: space-between;">

        <el-button type="primary" style="width: 100px;height: 40px;" @click="isInsert = true">添加商品</el-button>
    </el-row>







    <el-dialog v-model="isUpdate" title="修改商品" width="40%" style="border-radius: 10px;">
        <el-form label-position="left" label-width="150px" :model="goodsUpdateFrom" style="width: 80%;margin: 0 auto;"
            :rules="fromRules">
            <div style="font-size: 12px;color: gray;margin-bottom:30px;text-align: center;">*部分数据不予手动修改，将不进行展示*</div>
            <el-form-item label="商品ID（唯一键）">
                <el-input v-model="goodsUpdateFrom.gid" disabled />
            </el-form-item>
            <el-form-item label="商品名称" prop="name">
                <el-input v-model="goodsUpdateFrom.name" />
            </el-form-item>
            <el-form-item label="商品价格" prop="price">
                <el-input-number v-model="goodsUpdateFrom.price" :precision="1" :step="1" :min="0" :max="999999999" />
            </el-form-item>
            <el-form-item label="商品库存" prop="stock">
                <el-input-number v-model="goodsUpdateFrom.stock" :precision="0" :min="0" :max="100000" />
            </el-form-item>
            <el-form-item label="商品类型">
                <el-select v-model="goodsUpdateFrom.tid" placeholder="添加类型" size="large">
                    <el-option v-for="item in typeList" :key="item.tid" :label="item.name" :value="item.tid" />
                </el-select>
            </el-form-item>
            <el-form-item label="商品图片" prop="cover">

                <el-col>
                    <el-link :href="goodsUpdateFrom.cover" target="_blank" style="text-decoration: none;">
                        <el-tooltip :content="goodsUpdateFrom.cover" placement="top-start">
                            <el-image style="width: 100px;height: 100px;border: 1px lightgray solid;margin: 0 auto;"
                                :src="goodsUpdateFrom.cover" fit="cover">
                                <template #error>
                                    <el-text style="font-size: 14px;">
                                        {{ "图片无法展示" }}
                                    </el-text>
                                </template>
                            </el-image>
                        </el-tooltip>
                    </el-link>
                </el-col>

                <el-col>
                    <el-upload ref="upload_update" action="/api/upload/goods_cover" :limit="1" :on-exceed="(files) => {
                        this.$refs.upload_update.clearFiles();
                        this.$refs.upload_update.handleStart(files[0])
                    }" :on-success="handleSuccess_update" :auto-upload="false">
                        <template #trigger>
                            <el-button type="primary">更换图片</el-button>
                        </template>
                    </el-upload>
                </el-col>

            </el-form-item>
            <el-form-item label="商品描述" prop="intro">
                <el-input type="textarea" maxlength="50" show-word-limit autosize v-model="goodsUpdateFrom.intro" />
            </el-form-item>

        </el-form>
        <template #footer>
            <el-button @click="isUpdate = false">关闭</el-button>
            <el-button type="primary" @click="submit_updateGoods">提交</el-button>
        </template>
    </el-dialog>

    <el-dialog v-model="isInsert" title="添加商品" width="40%" style="border-radius: 10px;">
        <el-form label-position="left" label-width="150px" :model="goodsInsertFrom" style="max-width: 460px;margin: 0 auto;"
            :rules="fromRules">
            <div style="font-size: 12px;color: gray;margin-bottom:30px;text-align: center;">*部分数据无需手动添加，将不进行展示*</div>
            <el-form-item label="商品ID（唯一键）">
                <el-input v-model="goodsInsertFrom.gid" disabled />
            </el-form-item>
            <el-form-item label="商品名称" prop="name">
                <el-input v-model="goodsInsertFrom.name" />
            </el-form-item>
            <el-form-item label="商品价格" prop="price">
                <el-input-number v-model="goodsInsertFrom.price" :precision="1" :step="1" :min="0" :max="999999999" />
            </el-form-item>
            <el-form-item label="商品库存" prop="stock">
                <el-input-number v-model="goodsInsertFrom.stock" :precision="0" :min="0" :max="100000" />
            </el-form-item>
            <el-form-item label="商品类型">
                <el-select v-model="goodsInsertFrom.tid" placeholder="添加类型" size="large">
                    <el-option v-for="item in typeList" :key="item.tid" :label="item.name" :value="item.tid" />
                </el-select>
            </el-form-item>
            <el-form-item label="商品图片" prop="cover">

                <el-upload ref="upload" action="/api/upload/goods_cover" :limit="1" :on-exceed="(files) => {
                    this.$refs.upload.clearFiles();
                    this.$refs.upload.handleStart(files[0])
                }" :on-success="handleSuccess" :auto-upload="false">

                    <template #trigger>
                        <el-button type="primary">选择图片</el-button>
                    </template>
                </el-upload>
            </el-form-item>
            <el-form-item label="商品描述" prop="intro">
                <el-input type="textarea" maxlength="50" show-word-limit autosize v-model="goodsInsertFrom.intro" />
            </el-form-item>
        </el-form>
        <template #footer>
            <el-button @click="isInsert = false">关闭</el-button>
            <el-button type="primary" @click="submit_insertGoods">提交</el-button>
        </template>
    </el-dialog>
</template>

<script>
import axios from 'axios'
import { ElMessage } from 'element-plus'

axios.defaults.baseURL = '/api'

export default {
    data() {
        return {
            goodsData: [],
            typeList: [],
            isUpdate: false,
            goodsUpdateFrom: {},
            isInsert: false,
            goodsInsertFrom: {
                gid: '添加后自动生成',
                tid: '',
                name: '',
                cover: '无图片',
                price: 0,
                stock: 0,
                intro: '商品描述',
            },
            fromRules: {
                name: [
                    { required: true, message: '请输入商品名称', trigger: 'blur' }
                ],
                price: [
                    { required: true, message: '请输入商品单价', trigger: 'blur' },
                ],
                stock: [
                    { required: true, message: '请输入商品库存', trigger: 'blur' },
                ],
            },
        }
    },
    created() {
        this.getGoodsData()
        this.getTypeList()
    },
    methods: {
        getGoodsData() {
            axios.get('/goods')
                .then(result => {
                    if (result.data.code === 1) {
                        this.goodsData = result.data.data;
                    }
                })
                .catch(err => {
                    console.log(err);
                })
        },
        getTypeList() {
            axios.get('/type')
                .then(result => {
                    if (result.data.code === 1) {
                        this.typeList = result.data.data;
                    }
                })
                .catch(err => {
                    console.log(err);
                })
        },
        getTypeName(tid) {
            for (const k in this.typeList) {
                if (this.typeList[k].tid === tid) {
                    return this.typeList[k].name;
                }
            }
            return '-';
        },
        recommendGoods(goods) {
            let arr = [];
            arr.push(goods.gid);
            axios.post('/recommend/' + arr)
                .then(result => {
                    if (result.data.code === 1) {
                        ElMessage.success("推荐成功");
                    } else {
                        ElMessage.error("推荐失败");
                        console.log(result.data);
                    }
                })
                .catch(err => {
                    console.log(err);
                    if (err.response.status === 500) {
                        ElMessage.info("后端服务器出现异常");
                        return;
                    }
                    ElMessage.error("推荐失败！！！");
                })
        },
        deleteGoods(goods) {
            let arr = [];
            arr.push(goods.gid);
            axios.delete('/goods/' + arr)
                .then(result => {
                    if (result.data.code === 1) {
                        ElMessage.success("删除成功");
                        this.getGoodsData();
                    } else {
                        ElMessage.error("删除失败");
                        console.log(result.data);
                    }
                })
                .catch(err => {
                    console.log(err);
                    if (err.response.status === 500) {
                        ElMessage.info("后端服务器出现异常");
                        return;
                    }
                    ElMessage.error("删除失败！！！");
                })
        },
        updateGoods(goods) {
            this.goodsUpdateFrom = JSON.parse(JSON.stringify(goods));
            this.isUpdate = true;
        },
        submit_insertGoods() {
            this.$refs.upload.submit();
        },
        handleSuccess_insert(response) {
            if (response.code === 1) {
                this.goodsInsertFrom.cover = response.data;
            } else {
                ElMessage.info("商品封面图片上传失败！！！");
                console.log(response.data);
            }
            this.axios_insertGoods();
            this.$refs.upload.clearFiles();
        },
        axios_insertGoods() {
            const data = {
                tid: this.goodsInsertFrom.tid,
                name: this.goodsInsertFrom.name,
                cover: this.goodsInsertFrom.cover,
                price: this.goodsInsertFrom.price,
                stock: this.goodsInsertFrom.stock,
                intro: this.goodsInsertFrom.intro,
            }
            axios.post('/goods', data)
                .then(result => {
                    if (result.data.code === 1) {
                        ElMessage.success("添加成功");
                        this.getGoodsData();
                        this.isInsert = false;
                    } else {
                        if (result.data.msg === "name_exist") {
                            ElMessage.info("用户名 " + this.goodsInsertFrom.name + " 已被占用");
                            return;
                        }
                        ElMessage.info("添加失败");
                        console.log(result.data);
                    }
                })
                .catch(err => {
                    console.log(err);
                    if (err.response.status === 500) {
                        ElMessage.info("后端服务器出现异常");
                        return;
                    }
                    ElMessage.error("添加失败");
                })

        },
        submit_updateGoods() {
            this.$refs.upload_update.submit();
        },
        handleSuccess_update(response) {
            if (response.code === 1) {
                this.goodsUpdateFrom.cover = response.data;
            } else {
                ElMessage.info("商品封面图片上传失败！！！");
                console.log(response.data);
            }
            this.axios_updateGoods();
            this.$refs.upload_update.clearFiles();
        },
        axios_updateGoods() {
            const data = {
                gid: this.goodsUpdateFrom.gid,
                tid: this.goodsUpdateFrom.tid,
                name: this.goodsUpdateFrom.name,
                cover: this.goodsUpdateFrom.cover,
                price: this.goodsUpdateFrom.price,
                stock: this.goodsUpdateFrom.stock,
                intro: this.goodsUpdateFrom.intro,
            }
            axios.put('/goods', data)
                .then(result => {
                    if (result.data.code === 1) {
                        ElMessage.success("修改成功");
                        this.getGoodsData();
                        this.isUpdate = false;
                    } else {
                        if (result.data.msg === "name_exist") {
                            ElMessage.info("商品名称 " + this.goodsUpdateFrom.name + " 已被占用");
                            return;
                        }
                        ElMessage.info("添加失败");
                        console.log(result.data);
                    }
                })
                .catch(err => {
                    console.log(err);
                    ElMessage.error("异常！！！");
                    if (err.response.status === 500) {
                        ElMessage.info("后端服务器出现异常");
                    }
                })
        }
    }
}
</script>

<style scoped>
.my-h1 {
    color: #000;
    text-align: center;
    font-size: 28px;
    margin: 10px 0;
}

.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}

.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>

